//
//  picturePickerViewController.swift
//  照片选择
//
//  Created by 吴婷婷 on 15/11/17.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit

private let picturePickerViewId = "picturePickerViewId"

class PicturePickerViewController: UICollectionViewController {
    //用户当前选中按钮索引
    private var selectedIndex = 0
    //最大图片数量
    private let picturePickerMaxCount = 3
    //图片数组
    lazy var pictures = [UIImage]()
    
    //MARK: - 构造函数
    init() {
        
        super.init(collectionViewLayout: picturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView!.backgroundColor = UIColor(white: 0.95, alpha: 1)
        // Register cell classes
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: picturePickerViewId)

    }
    //MARK: - 自定义flowLayout
    private class picturePickerLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            
            let count: CGFloat = 4
            let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * margin) / count
            
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        }
    }
}
    // MARK: - UICollectionViewDataSource
extension PicturePickerViewController
{

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        
        return pictures.count + (pictures.count == picturePickerMaxCount ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(picturePickerViewId, forIndexPath: indexPath) as! PicturePickerCell
        //设置代理
        cell.pictureDelegate = self
        //设置图片
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item]: nil
    
        return cell
    }
}

//Mark: - PicturePickerCelldelegate
extension PicturePickerViewController: PicturePickerCelldelegate {
    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("不允许访问照片库")
            return
        }
        
        let picker = UIImagePickerController()
        //记录用户选中索引
        selectedIndex = collectionView!.indexPathForCell(cell)!.item
        
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {

        let index = collectionView?.indexPathForCell(cell)!.item
        
        pictures.removeAtIndex(index!)
        
        collectionView?.reloadData()
        
    }
}
//MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PicturePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        let scaleImage = image.scaleToWidth(600)
        if selectedIndex < pictures.count {
            pictures[selectedIndex] = image
        } else {
            pictures.append(scaleImage)
        }
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}


//Mark: - picturePickerCelldelegate
@objc private protocol PicturePickerCelldelegate : NSObjectProtocol {
    
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)
}

//MARK: - picturePickerCell
private class PicturePickerCell: UICollectionViewCell {
    //图片
    private var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            
            deleteButton.hidden = (image == nil)
        }
    }
    //代理
    weak var pictureDelegate: PicturePickerCelldelegate?
    
    //MARK: - 监听方法
    @objc func addPicture(){
        pictureDelegate?.picturePickerCellDidAdd?(self)
    }
    @objc func removePicture(){
        pictureDelegate?.picturePickerCellDidRemove?(self)
    }
   // MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 设置界面
    func setupUI() {
        //添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        
        //设置布局
        addButton.frame = bounds
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(addButton.snp_right)
            make.top.equalTo(addButton.snp_top)
        }
        //监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        deleteButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    
    //MARK: - 懒加载
    lazy var addButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    lazy var deleteButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}








